<template>
	<div>
		<headNav title="亲情留言"></headNav>
		<classNav :title="studentName"></classNav>
		<div class="main" ref="main" @scroll="scroll">
			<!-- <uptoScroll @loadMore='loadMore'> -->
			<div class="load-p">
				<load-more v-if="isLoading" :tip="'正在加载'"></load-more>
				<load-more v-if="!isMore" :show-loading="false" :tip="'没有更多了'" background-color="#fbf9fe"></load-more>
			</div>
			<div v-for="(item, index) in chatList" :key="index" class="listBox">
				<div class="time">
					{{item.time | chatTime}}
				</div>
				<div v-for="(item2, index2) in item.arr" :key="index2" class="oneBox">
					<div class="mine" v-if="item2.isMine">
						<img v-if="item2.chatUserImageUrl" :src="item2.chatUserImageUrl" @error="defaultBackImg" alt="">
						<img v-else src="@/assets/img/default_head.png" alt="">
						<span class="chatContent" v-if="item2.msgType == 0">
							{{item2.content}}
						</span>
						<span class="chatContent audio" v-else @click="player(item2)">
							<audio :src='item2.content' :id='item2.content'></audio>
							<img v-if="item2.isPlay" src="@/assets/img/homeWork/a-2.gif" alt="">
							<img v-else src="@/assets/img/weChat/audio.png" alt="">
							{{item2.voiceTotalSeconds}}"
						</span>
					</div>
					<div class="other" v-else>
						<img v-if="item2.chatUserImageUrl" :src="item2.chatUserImageUrl" @error="defaultBackImg" alt="">
						<img v-else src="@/assets/img/default_head.png" alt="">
						<span class="nameBox">
							<p class="nickname">{{item2.chatUserNickName}}</p>
							<span class="chatContent" v-if="item2.msgType == 0">
								{{item2.content}}
							</span>
							<span class="chatContent audio" v-else @click="player(item2)">
								<audio :src='item2.content' :id='item2.content'></audio>
								<img v-if="item2.isPlay" src="@/assets/img/voiceGif.gif" alt="">
								<img v-else src="@/assets/img/weChat/audio2.png" alt="">
								{{item2.voiceTotalSeconds}}"
							</span>
						</span>
						<span class="cycle" v-if="!item2.hasRead && item2.msgType == 1"></span>
					</div>
				</div>
			</div>
			<!-- </uptoScroll> -->
		</div>
		<div class="footer" v-if="isMain">
			<div class="voiceBox">
				<voice @upLoad='upLoad'></voice>
			</div>
			<input type="text" v-model.trim="chatContent" @input="input" maxlength="120">
			<div v-show="showSend" class="imgBox" @click="sendMsg(true)">
				<img src="@/assets/img/weChat/send.png" alt="">
			</div>
		</div>
	</div>
</template>
<script>
import headNav from '@/components/headNav/headNav'
import classNav from './classNav'
import { LoadMore } from 'vux'
import voice from './audio'
import uptoScroll from '@/components/uptoScroll'
export default {
	components: {
		headNav, classNav, voice, uptoScroll, LoadMore
	},
	data() {
		return {
			time: -1,
			interval: null,
			isLoading: false,
			isMore: true,
			chatContent: '',
			pageNum: 0,
			pageSize: 10,
			lastVoice: '',
			chatList: [],
			curVoice: { url: 'https://www.w3cschool.cn/statics/demosource/horse.ogg' },
			isTop: false,
            showSend: false,
            isMain: true
		}
	},
	computed: {
		chatObj() {
			return this.$store.state.weChat.chatObj
		},
		roleCode() {
			return this.$store.state.user.roleCode
		},
		studentName() {
			return this.roleCode == 'Teacher' ? this.chatObj.name : this.$store.state.user.studentName
        },
        classId () {
            return this.$store.state.user.classId
        },
        classList () {
            return this.$store.state.user.classList
        },
	},
	mounted() {
		this.getChatDetail().then(
			() => {
				this.scrollBot()
			}
		)
        this.timer()
        this.checkMain()
	},
	destroyed() {
		clearTimeout(this.interval)
	},
	methods: {
        checkMain () {
            this.classList.forEach(
                item => {
                    if (item.ClassId == this.classId) {
                        this.isMain = item.IsMain
                    }
                }
            )
        },
		timer() {
			this.time++
			if (this.time >= 59) {
				this.chatList = []
				this.isTop = true
				this.pageNum = 0
				this.isMore = true
				this.getChatDetail().then(
					() => {
						this.scrollBot()
						this.isTop = false
					}
				)
				this.time = -1
			}
			this.interval = setTimeout(() => {
				this.timer()
			}, 1000)
		},
		input() {
			if (this.chatContent) {
				this.showSend = true
			} else {
				this.showSend = false
			}
		},
		defaultBackImg() {
			if (event.type == "error") {
				event.target.src = require("../../assets/img/default_head.png")
			}
		},
		scroll(e) {
			if (e.target.scrollTop == 0) {
				this.loadMore()
			}
		},
		upLoad() {
			this.$store.dispatch('media/upload').then(() => {
				this.sendMsg(false)
			})
		},
		scrollBot() {
			this.$nextTick(
				() => {
					if (this.$refs.main.scrollHeight > this.$refs.main.clientHeight) {
						this.$refs.main.scrollTop = this.$refs.main.scrollHeight
					}
				}
			)
		},
		loadMore() {
			if (this.isTop) {
				return
			}
			this.isLoading = true
			this.isMore = true
			this.getChatDetail()
		},
		sendMsg(flag) {
			var params = {
				studentId: this.roleCode == 'Teacher' ? this.chatObj.id : this.$store.getters['user/studentId'],
				msgType: flag ? 0 : 1,
				content: flag ? this.chatContent : this.$store.state.media.voices.join(),
				sendUserType: this.roleCode == 'Teacher' ? 2 : 1,
				sendUserKeyId: this.roleCode == 'Teacher' ? this.$store.getters['user/teacherId'] : this.$store.getters['user/parentId'],
				chatTargetType: this.roleCode == 'Teacher' ? 1 : 0,
				voiceTotalSeconds: flag ? 0 : this.$store.state.media.timeList.join()
			}
			this.$store.dispatch('weChat/SendChatMsg', params).then(
				res => {
					this.chatContent = ''
					this.showSend = false
					this.chatList = []
					this.isTop = true
					this.pageNum = 0
					this.isMore = true
					this.getChatDetail().then(
						() => {
							this.scrollBot()
							this.isTop = false
						}
					)
				}
			)
		},
		// 获取聊天详情
		getChatDetail() {
			if (!this.isMore) {
				return
			}
			this.pageNum++
			var params = {
				ChatContentBatchId: '',
				StudentId: this.roleCode == 'Teacher' ? this.chatObj.id : this.$store.getters['user/studentId'],
				ClassId: this.$store.state.user.classId,
				PageNum: this.pageNum,
				PageSize: this.pageSize
			}
			return new Promise((resolve, reject) => {
				this.$store.dispatch('weChat/GetSchoolChatDetail', params).then(
					res => {
						this.isLoading = false
						var firstTime = ''
						var firstTimeLess = ''
						var arr = []
						var chatArr = []
						if (res.items.length < this.pageSize) {
							this.isMore = false
						}
						res.items.reverse()
						res.items.forEach((item, index) => {
                            item.creationTime= item.creationTime.replace(/-/g,"/")
                            item.creationTime= item.creationTime.replace(/T/g," ")
							item.isMine = false
							item.isPlay = false
							var chatId = this.$store.state.user.roleCode == 'Teacher' ? this.$store.state.user.teacherId : this.$store.state.user.parentId
							if (item.chatUserKeyId == chatId) {
								item.isMine = true
							}
							if (res.items.length == 1) {
								firstTimeLess = (new Date(item.creationTime)).getTime()
								firstTime = item.creationTime
								arr.push(item)
								var obj = { time: firstTime, arr: arr }
								chatArr.push(obj)
							} else {
								if (!firstTimeLess) {
									firstTimeLess = (new Date(item.creationTime)).getTime()
									firstTime = item.creationTime
									arr.push(item)
								} else {
									var timeLess = (new Date(item.creationTime)).getTime()
									if (timeLess - firstTimeLess <= 300000) {
										arr.push(item)
									} else {
										if (arr.length > 0) {
											var obj = { time: firstTime, arr: arr }
											chatArr.push(obj)
										}
										firstTime = item.creationTime
										firstTimeLess = (new Date(item.creationTime)).getTime()
										arr = []
										arr.push(item)
									}
									if (res.items.length - 1 == index) {
										if (arr.length > 0) {
											var obj = { time: firstTime, arr: arr }
											chatArr.push(obj)
										}
									}
								}
							}
						})
						this.chatList = chatArr.concat(this.chatList)
						resolve()
					}
				)
			})
		},
		// 
		player(curVoice) {
			if (!curVoice.hasRead) {
				var params = {
					chatContentId: curVoice.chatContentId,
					orderNum: curVoice.orderNum,
					isRead: true
				}
				this.$store.dispatch('weChat/MsgReadState', params).then(
					res => {
						curVoice.hasRead = true
						this.play(curVoice)
					}
				)
			} else {
				this.play(curVoice)
			}
		},
		// 播放语音
		play(curVoice) {
			if (this.lastVoice.content && this.lastVoice.content != curVoice.content) {
				document.getElementById(this.lastVoice.content).pause()
				document.getElementById(this.lastVoice.content).load()
				this.lastVoice.isPlay = false
			}
			var music = document.getElementById(curVoice.content)
			if (music.paused) {
				music.play()
				curVoice.isPlay = true
				this.lastVoice = curVoice
			} else {
				music.pause()
				music.load()
				curVoice.isPlay = false
			}
			var isend = document.getElementById(curVoice.content)
			isend.addEventListener('ended', function () {
				curVoice.isPlay = false
			}, false)
		},
	}
}
</script>
<style lang='less' scoped>
.main {
	padding: 0 0.24rem 1.48rem 0.24rem;
	height: calc(100% - 0.88rem);
	overflow: auto;
	box-sizing: border-box;
}
.time {
	color: #999999;
	text-align: center;
	padding: 0.3rem 0;
	font-size: 0.26rem;
}
.listBox {
	.oneBox {
		margin-bottom: 0.3rem;
	}
	.oneBox:last-child {
		margin-bottom: 0;
	}
}
.other,
.mine {
	> img {
		vertical-align: top;
		width: 0.72rem;
		height: 0.72rem;
		border-radius: 50%;
		object-fit: cover;
	}
}
.audio {
	min-width: 1.3rem;
}
.cycle {
	position: relative;
	top: 0.2rem;
	display: inline-block;
	width: 0.12rem;
	height: 0.12rem;
	border-radius: 50%;
	background: #ff0000;
	vertical-align: middle;
	margin-left: 0.04rem;
}
.chatContent {
	display: inline-block;
	padding: 0 0.3rem;
	height: 0.8rem;
	line-height: 0.8rem;
	border-radius: 0.6rem;
	vertical-align: top;
	font-size: 0.26rem;
	vertical-align: middle;
	> img {
		width: 0.24rem;
		height: 0.36rem;
		vertical-align: text-bottom;
		margin-right: 0.1rem;
	}
}
.other {
	> .nameBox {
		display: inline-block;
		margin-left: 0.16rem;
	}
	.chatContent {
		vertical-align: top;
		background: #fff;
		color: #666666;
	}
	.nickname {
		font-size: 0.16rem;
		margin-bottom: 0.06rem;
	}
}
.mine {
	direction: rtl;
	> .chatContent {
		direction: ltr;
		margin-right: 0.16rem;
		color: #fff;
		background: #128fef;
	}
}
.footer {
	position: fixed;
	bottom: 0;
	width: 100%;
	padding: 0.24rem;
	background: #fff;
	input {
		width: 4.72rem;
		height: 0.72rem;
		border-radius: 0.36rem;
		background: #e6e6e6;
		vertical-align: middle;
		margin: 0 0.2rem;
		font-size: 0.26rem;
		color: #000;
		padding: 0 0.36rem;
		box-sizing: border-box;
	}
	.voiceBox {
		display: inline-block;
	}
	.imgBox {
		vertical-align: middle;
		display: inline-block;
		padding: 0.18rem 0.18rem 0.14rem 0.18rem;
		border-radius: 50%;
		background: #128fef;
		img {
			width: 0.33rem;
			height: 0.33rem;
		}
	}
}
.load-p {
	padding: 0.1rem 0 0 0;
}
</style>